<?php

// Copyright 2019 Hackware SpA <human@hackware.cl>
// "Hackware Web Services Core" is released under the MIT License terms.

namespace Hawese\Tests;

use Hawese\Core\Http\Controllers\Paginator;
use Laravel\Lumen\Testing\DatabaseTransactions;

class PaginatorTest extends TestCase
{
    use DatabaseTransactions;

    private const LIMIT = 10;

    public function setUp(): void
    {
        parent::setUp();

        for ($i = 0; $i < 21; $i++) {
            (new DumbTableModel([
                'attr1' => bin2hex(random_bytes(12))
            ]))->insert();
        }

        $this->paginator = new Paginator(
            DumbTableModel::select(),
            1,
            self::LIMIT
        );
    }

    public function testTotalPages()
    {
        $this->assertSame(3, $this->paginator->totalPages());
    }

    public function testGet()
    {
        $this->assertSame(self::LIMIT, $this->paginator->get()->count());
        $this->assertSame(
            1,
            (new Paginator(DumbTableModel::select(), 3, self::LIMIT))->get()
                                                                     ->count()
        );
    }

    public function testLinks()
    {
        $links = $this->paginator->links(
            'https://request/url/',
            ['unrelated' => 1, 'query' => 2, 'params' => 3]
        );
        $this->assertStringContainsString('page=1', $links['first']);
        $this->assertStringContainsString('page=3', $links['last']);
        $this->assertSame(null, $links['prev']);
        $this->assertStringContainsString('page=2', $links['next']);
        $this->assertStringContainsString('unrelated=1', $links['next']);

        $lastPagePaginator = new Paginator(
            DumbTableModel::select(),
            3,
            self::LIMIT
        );
        $this->assertSame(
            null,
            $lastPagePaginator->links('https://request/url/')['next']
        );
    }
}
